<?php

use App\Admin\Controllers\DashboardController;
use App\Admin\Controllers\DemoController;
use App\Admin\Controllers\HomeController;
use App\Admin\Controllers\LoginController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use LowCode\Block;
use LowCode\Core\Admin;
use LowCode\Core\Response;
use LowCode\Menu;
use LowCode\Page;
use LowCode\Support\JsDs;
use LowCode\UI;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/__vtj__/', function () {
    return view('lowcode');
});
//Route::get('/dist/__vtj__', function () {
//    return view('lowcode');
//});

Route::group([
    "prefix"=>"__vtj__"
], function () {

    Route::group([
        "prefix"=>"api"
    ], function () {
        Route::post('init.json', function () {
            return response(file_get_contents(public_path("__vtj__api/init.json")));
        });

        Route::post("getFile.json",function (){
            $key = \request()->post("data");
//            $content = file_get_contents(public_path("__vtj__api/file.json"));
            $content = Cache::get($key);
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>json_decode($content,true)
            ]);
        });
        Route::post("saveFile.json",function (){
            $data = \request()->post("data");
            $key = "file_".$data['id'];
            $content = json_encode($data,JSON_UNESCAPED_UNICODE);
            Cache::set($key, $content);
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>true
            ]);
        });

        Route::post("saveMaterials.json",function (){
            $data = request()->post("data");
            if ($data){
                Cache::set("__vtj__Materials", $data);
            }
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>true
            ]);
        });
        Route::post("getHistory.json",function (){
            $fId = request()->post("data");
            $key = "history_".$fId;
            $content = Cache::get($key);
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>json_decode($content, true)
            ]);
        });
        Route::post("saveHistoryItem.json",function (){
            $data = request()->post("data");
            $key = "history_item_".$data['fId'];
            $item = $data['item'];
//            $content = Cache::get($key);
//            if ($content){
//                $content = json_decode($content, true);
//                $items = collect($content['items']);
//                $isEmpty = $items->where("id",$item['id'])->isEmpty();
//                if ($isEmpty){
//                    $items->add($item);
//                }else{
//                    $content['items'][] = $item;
//                }
//            }else{
//                $content['items'] = [$item];
//            }
//            Cache::set($key, json_encode($content,JSON_UNESCAPED_UNICODE));
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>true
            ]);
        });
        Route::post("removeHistoryItem.json",function () {
            $data = request()->post("data");
            $key = "history_item_".$data['fId'];
            $ids = $data['ids'];
//            if ($ids){
//                $content = Cache::get($key);
//                if ($content){
//                    $content = json_decode($content, true);
//                    collect($content['items'])->whereIn("id",$ids)->remember();
//                }
//            }
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>true
            ]);
        });

        Route::post("saveHistory.json",function (){
            $data = request()->post("data");
            $key = "history_".$data['id'];
            Cache::set($key, json_encode($data,JSON_UNESCAPED_UNICODE));
            return response()->json([
                'code'=>0,'msg'=>'success','success'=>true, 'data'=>true
            ]);
        });

    });
//    Route::get('api', function () {
//        return "https://sso-sit.newpearl.com";
//    });
//    return "https://sso-sit.newpearl.com";
});



Route::group([
    "prefix"=>"admin-api",
    "name"=>"admin-api.",
],function (){
    Route::get("/home", [HomeController::class, "index"]);
    Route::get("/analytics", [DashboardController::class, "analytics"]);
    Route::get("/workspace", [DashboardController::class, "workspace"]);

    Route::get("/components", [HomeController::class, "component"]);
    Route::get("/views", [HomeController::class, "views"]);
    Route::get("/naive/index", [HomeController::class, "analytics"]);
    Route::get("/naive/table", [HomeController::class, "workspace"]);
    Route::get("/about", [HomeController::class, "about"]);
    Route::get("/about/index", [HomeController::class, "about"]);
    Route::get("/install", [HomeController::class, "install"]);

    Route::group([
        "prefix"=>"demo",
        "name"=>"demo.",
    ],function (){
        Route::get("/button", [DemoController::class, "button"]);

        Route::post("/list", function (){
            return response()->json([
                "code"=>0,
                "success"=>true,
                "data"=>[
                    "currentPage"=>1,
                    "pageSize"=>10,
                    "total"=>3,
                    "records"=>[
                        ['id'=>1,'name'=>"小米","age"=>"1"],
                        ['id'=>2,'name'=>"小孩","age"=>"2"],
                        ['id'=>3,'name'=>"小哥","age"=>"3"],
                    ]

                ]
            ]);
        });
    });

    Route::get("/test",function (){
        $el = UI::node("div");
        $el->props(['text'=>"111"]);
        $block = Block::make("block");
        $block->prop("test", 'String');
        $block->nodes([$el]);
        $block->dataSource("test", JsDs::make("test"));
        return response()->json([
            "code"=>0,
            "success"=>true,
            "data"=>$block
        ]);
    });
    Route::get("auth/{module}", [LoginController::class, "index"]);

    Route::post("auth/login",function (){
        return response()->json([
            "code"=>0,
            "error"=>null,
            "data"=>[
                "id"=> 1,
                "password"=> '123456',
                "realName"=> 'Admin',
                "roles"=> ['admin'],
                "username"=> 'admin',
                "accessToken"=> Hash::make(123456)
            ]
        ]);
    });
    Route::post("auth/logout",function (){

    });
    Route::get("auth/codes",function (){
        return response()->json([
            "code"=>0,
            "error"=>null,
            "data"=>[
                "codes"=> ['AC_100100', 'AC_100110', 'AC_100120', 'AC_100010'],
                "username"=> 'admin',
            ]
        ]);
    });



    Route::get("user/info",function (){
        return response()->json([
            "code"=>0,
            "error"=>null,
            "data"=>[
                "id"=> 1,
                "password"=> '123456',
                "realName"=> 'Admin',
                "roles"=> ['admin'],
                "username"=> 'admin',
                "avatar"=> "https://unpkg.com/@vbenjs/static-source@0.1.6/source/avatar-v1.webp",
                "accessToken"=> Hash::make(123456)
            ]
        ]);
    });

    Route::get("menu/all",function (){
        $menus = Menu::getMenus(app_path("menu.php"));
        return response()->json([
            "code"=>0,
            "error"=>null,
            "data"=>$menus
        ]);
    });

    Route::post("/upload", function (Request $request){
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $filename = time().'_'.$file->getClientOriginalName();
            $file->storeAs('uploads', $filename, 'public');
            // 存储文件，并生成公开链接
            $url = Storage::url("uploads/".$filename);
            return response()->json([
                "code"=>1,
                "message"=>"文件上传成功",
                "error"=>"null",
                "data"=>["url"=>env('app_url').$url]
            ]);
        }
        return response()->json([
            "code"=>1,
            "error"=>"null",
            "message"=>"上传错误",
        ]);
//        return back()->with('error', '请选择一个文件上传。');
    });
});

//Route
Route::fallback(function () {
    $block = Block::make("FallbackBlock", function (Block $block){
        $block->nodes(UI::fallback("404")->style("height","calc(100vh - 175px)"));
    });
    $page = Page::make($block);
    return response()->json(Response::success("ok",$page));
});
